<template>
  <div id="app">
    <router-view />
  </div>
</template>

<script>
import store from '@/store'
export default {
  name: 'App',
  data () {
    return {
      gap_time: 0,
      beforeUnload_time: 0
    }
  },
  methods: {
    // 关闭窗口之前执行
    beforeunloadHandler () {
      // 获取时间戳
      this.beforeUnload_time = new Date().getTime()
      console.log(1)
    },
    unloadHandler () {
      console.log(2)
      this.gap_time = new Date().getTime() - this.beforeUnload_time
      // 判断是窗口关闭还是刷新 毫秒数判断 网上大部分写的是5
      if (this.gap_time <= 10) {
        // 退出登录接口 这里应当换为个人的登出方法
        store.dispatch('user/logout')
      } else {
      }
    },
    // 网络连接成功
    network () {
      console.log('3');
    }
  },
  destroyed () {
    // 移除监听
    window.removeEventListener('beforeunload', () => this.beforeunloadHandler())
    window.removeEventListener('unload', () => this.unloadHandler())
  },
  mounted () {
    // 监听浏览器关闭
    window.addEventListener('beforeunload', () => this.beforeunloadHandler())
    window.addEventListener('unload', () => this.unloadHandler())
    // console.log('执行之前');
    window.addEventListener('online', () => this.network())
    // console.log('执行之后');
  }
}
</script>
